package com.cuitrip.business.tripservice;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.cuitrip.business.location.map.GaoDeMapActivity;
import com.cuitrip.business.tripservice.model.SelectMenu;
import com.cuitrip.business.tripservice.ui.SelectMenuFragment;
import com.cuitrip.business.tripservice.ui.SelectTwoMenuFragment;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.service.R;
import com.cuitrip.util.GaoDeMapController;
import com.cuitrip.util.GoogleMapController;
import com.cuitrip.util.MapController;
import com.cuitrip.util.MapUtil;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.text.TextProxy;
import com.cuitrip.util.track.TrackUtil;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.utils.ArrayUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Bind;
import butterknife.OnClick;


/**
 * 预约要求
 * Created  ak
 */
public class TripDemandInstructionActivity extends CustomUiFragmentActivity /*implements OnMapReadyCallback*/ {

    public static final String LATITUDE_KEY = "latitude";
    public static final String LONGTITUDE_KEY = "longtitude";
    public static final String MEETINGPLACE_KEY = "meetingPlace";
    public static final String ADVANCE_DAY_KEY = "advance_day";
    public static final String PERSON_MIN_KEY = "min_people";
    public static final String PERSON_MAX_KEY = "max_people";
    public static final String DURATION_KEY = "duration";
    public static final String BESTTIME_KEY = "besttime";


    @Bind(R.id.order_person_layout)
    protected ItemLayout mOrderPersonNumContent;

    @Bind(R.id.order_advance_layout)
    protected ItemLayout mOrderAdvanceNum;

    @Bind(R.id.order_duration_layout)
    protected ItemLayout mOrderDuration;

    @Bind(R.id.order_location_layout)
    protected ItemLayout mOrderLocationLayout;

    @Bind(R.id.full_content)
    protected View mFullContent;


    private String meetingPlace;
    private String latitude;
    private String longtitude;
    private int advanceDay;
    private int minPeople;
    private int maxPeople;
    private String duration;
    private String bestTime;
    private ServiceInfo serviceInfo;

    private List<Integer> advanceDayList = new ArrayList<>();
    private List<Integer> durationHourList = new ArrayList<>();
    private List<SelectMenu> timeList = new ArrayList<>();
    private List<SelectMenu> minPeopleMenuList = new ArrayList<>();
    private List<SelectMenu> maxPeopleMenuList = new ArrayList<>();
    private static final int ADVANCE_DAY = 7;
    private static final int DURATION_HOUR = 12;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (getIntent().hasExtra(TripEditActivity.SERVICE_INFO_KEY)){
            serviceInfo = (ServiceInfo) getIntent().getSerializableExtra(TripEditActivity.SERVICE_INFO_KEY);
        }
        super.onCreate(savedInstanceState,R.layout.page_demand_instruction);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        init();
    }

    private void initAdvanceDayList(){
        for (int i = 1; i <= ADVANCE_DAY; i++){
            advanceDayList.add(i);
        }
    }

    @Override
    public void initData() {
        initAdvanceDayList();
        initDurationList();
        initPeopleList();
        initValue();
    }

    private void initValue(){
        if (serviceInfo != null){
            if (serviceInfo.getPreOrderDays() != 0){
                advanceDay = serviceInfo.getPreOrderDays();
                bindPreOrderDays();
            }
            if (!TextUtils.isEmpty(serviceInfo.getServiceTime())){
                duration = serviceInfo.getServiceTime();
                bestTime = serviceInfo.getBestTime();
                bindDuration();
            }
            if (serviceInfo.getMaxbuyerNum() != 0 && serviceInfo.getMinBuyerNum() != 0){
                minPeople = serviceInfo.getMinBuyerNum();
                maxPeople = serviceInfo.getMaxbuyerNum();
                 mOrderPersonNumContent.setmRightText(bindPersonNum(minPeople,maxPeople));
            }
            if (!TextUtils.isEmpty(serviceInfo.getMeetingPlace())){
                meetingPlace = serviceInfo.getMeetingPlace();
                bindMeetingPlace();
            }
            if (!TextUtils.isEmpty(serviceInfo.getLat())&& !TextUtils.isEmpty(serviceInfo.getLng())){
                longtitude = serviceInfo.getLng();
                latitude = serviceInfo.getLat();
            }

        }
    }

    private void bindPreOrderDays(){
        String text = TextProxy.getInstance().formatWithSingleAndMore(advanceDay, R.string.trip_attribute_advance_value_one, R.string.trip_attribute_advance_value_more);
        mOrderAdvanceNum.setmRightText(text);
    }

    private void bindDuration(){
        String text = TextProxy.getInstance().formatWithSingleAndMore(duration, R.string.trip_attribute_duration_value_one, R.string.trip_attribute_duration_value_more);
        mOrderDuration.setmRightText(text);
    }

    public static String bindPersonNum(int minPeople, int maxPeople){
        if (minPeople != maxPeople){
            return  minPeople + " - "  + ResourceUtil.getString(R.string.trip_attribute_capacity_value_more, maxPeople);
        }else{
            String peopleText = TextProxy.getInstance().formatWithSingleAndMore(minPeople,R.string.trip_attribute_capacity_value_one,R.string.trip_attribute_capacity_value_more);
            return peopleText;
        }



    }

    private void bindMeetingPlace(){
        mOrderLocationLayout.setmRightText(meetingPlace);
        mOrderLocationLayout.setShowRightIcon(false);
        findViewById(R.id.mapViewContainer).setVisibility(View.VISIBLE);
    }



    @OnClick(R.id.order_person_layout)
    public void navigatePersonLayout(){
        SelectTwoMenuFragment selectTwoMenuFragment = new SelectTwoMenuFragment();
        selectTwoMenuFragment.setTitle(getString(R.string.trip_attribute_capacity_desc));
        selectTwoMenuFragment.setOnDataSource(new SelectTwoMenuFragment.OnDataSource() {

            @Override
            public List<SelectMenu> onFirstSource() {
                return minPeopleMenuList;
            }

            @Override
            public List<SelectMenu> onSecondSource(int position, SelectMenu firstMenu) {
                List<SelectMenu> secondMenuList = new ArrayList<>();
                if (ArrayUtil.isIndexSafe(position, maxPeopleMenuList)){
                    int lastIndex = maxPeopleMenuList.size();
                    List<SelectMenu> subList = maxPeopleMenuList.subList(position, lastIndex);
                    secondMenuList.addAll(subList);
                    return secondMenuList;
                }
                return null;

            }

        });
        selectTwoMenuFragment.setResultListener(new SelectTwoMenuFragment.OnTwoDataSelectBackListener() {
            @Override
            public void onSelect(SelectMenu firstSelectMenu, SelectMenu secondSelectMenu) {
                minPeople = Integer.parseInt(firstSelectMenu.key);
                maxPeople = Integer.parseInt(secondSelectMenu.key);
                mOrderPersonNumContent.setmRightText(bindPersonNum(minPeople, maxPeople));
            }
        });
        showDialogFragment(selectTwoMenuFragment);
    }

    @OnClick(R.id.order_advance_layout)
    public void selectAdvanceDays() {
        SelectMenuFragment selectMenuFragment = new SelectMenuFragment();
        List<SelectMenu> selectMenuList = new ArrayList<>();
        for (int i = 0 ; i < advanceDayList.size() ; i++){
            SelectMenu selectMenu = new SelectMenu();
            int dayValue = advanceDayList.get(i);
            selectMenu.key = String.valueOf(dayValue);
            if (dayValue > 1){
                selectMenu.value = getString(R.string.trip_attribute_advance_value_more, dayValue);
            }else{
                selectMenu.value = getString(R.string.trip_attribute_advance_value_one, dayValue);
            }
            selectMenuList.add(selectMenu);
        }
        selectMenuFragment.setTitle(getString(R.string.trip_attribute_advance_desc));
        selectMenuFragment.setSelectMenuList(selectMenuList);
        showDialogFragment(selectMenuFragment);
        selectMenuFragment.setResultListener(new SelectMenuFragment.OnDataSelectBackListener() {
            @Override
            public void onSelect(SelectMenu selectMenu) {
                advanceDay = Integer.parseInt(selectMenu.key);
                bindPreOrderDays();
            }
        });



    }

    private void initPeopleList(){
        for (int i = 1; i <= 6; i++){
            SelectMenu minPeopleMenu = new SelectMenu();
            minPeopleMenu.key = String.valueOf(i);
            minPeopleMenu.value = TextProxy.getInstance().formatWithSingleAndMore( i ,R.string.trip_attribute_capacity_value_min_one,R.string.trip_attribute_capacity_value_min_more);
            minPeopleMenuList.add(minPeopleMenu);

            SelectMenu maxPeopleMenu = new SelectMenu();
            maxPeopleMenu.key = String.valueOf(i);
            maxPeopleMenu.value = TextProxy.getInstance().formatWithSingleAndMore( i ,R.string.trip_attribute_capacity_value_max_one,R.string.trip_attribute_capacity_value_max_more);
            maxPeopleMenuList.add(maxPeopleMenu);
        }
    }



    private void initDurationList(){
        for (int i = 0; i <= 23; i++){
            StringBuilder stringBuilder = new StringBuilder();
            if (i < 10){
                stringBuilder.append(0).append(i);
            }else{
                stringBuilder.append(i);
            }
            stringBuilder.append(":00");
            SelectMenu selectMenu = new SelectMenu();
            selectMenu.key = String.valueOf(i);
            selectMenu.value = stringBuilder.toString();
            timeList.add(selectMenu);
        }
    }


    @OnClick(R.id.order_duration_layout)
    public void selectDuration() {
        SelectTwoMenuFragment selectTwoMenuFragment = new SelectTwoMenuFragment();
        selectTwoMenuFragment.setTitle(getString(R.string.trip_attribute_duration_desc));
        selectTwoMenuFragment.setOnDataSource(new SelectTwoMenuFragment.OnDataSource() {

            @Override
            public List<SelectMenu> onFirstSource() {
                return timeList;
            }

            @Override
            public List<SelectMenu> onSecondSource(int position, SelectMenu firstMenu) {
                List<SelectMenu> secondMenuList = new ArrayList<>();
                if (ArrayUtil.isIndexSafe(position + 1, timeList)){
                    int lastIndex = timeList.size() - position > 12 ? position + 13 : timeList.size();
                    List<SelectMenu> subList = timeList.subList(position + 1, lastIndex);
                    secondMenuList.addAll(subList);
                    return secondMenuList;
                }
                return secondMenuList;
            }

        });
        selectTwoMenuFragment.setResultListener(new SelectTwoMenuFragment.OnTwoDataSelectBackListener() {
            @Override
            public void onSelect(SelectMenu firstSelectMenu, SelectMenu secondSelectMenu) {
                duration = String.valueOf(Integer.parseInt(secondSelectMenu.key) - Integer.parseInt(firstSelectMenu.key));
                bestTime = firstSelectMenu.key;
                bindDuration();
            }
        });
        showDialogFragment(selectTwoMenuFragment);
    }

    @OnClick(R.id.order_location_layout)
    public void selectLocation(){
        if (serviceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()){
            TrackUtil.trackScreenName("/insider/trips/create/set/booking/meeting");
        }else{
            TrackUtil.trackScreenName("/insider/trips/edit/set/booking/meeting");
        }
        MapUtil.getDefaultInstance().searchMap(this, latitude, longtitude,meetingPlace);
    }

    @Override
    public void onBackPressed() {
        saveAction();
    }

    private void saveAction(){
        setResult();
        finish();
    }

    private void setResult(){
        Intent intent = new Intent();
        intent.putExtra(MEETINGPLACE_KEY, meetingPlace);
        intent.putExtra(LATITUDE_KEY, latitude);
        intent.putExtra(LONGTITUDE_KEY, longtitude);
        intent.putExtra(ADVANCE_DAY_KEY, advanceDay);
        intent.putExtra(PERSON_MIN_KEY, minPeople);
        intent.putExtra(PERSON_MAX_KEY, maxPeople);
        intent.putExtra(DURATION_KEY, duration);
        intent.putExtra(BESTTIME_KEY, bestTime);
        setResult(RESULT_OK, intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode!=RESULT_OK){
            return;
        }
        if (requestCode == GaoDeMapActivity.REQUEST){
            meetingPlace = GaoDeMapActivity.getName(data);
            latitude = String.valueOf(GaoDeMapActivity.getLat(data));
            longtitude = String.valueOf(GaoDeMapActivity.getLng(data));
        }
        if (requestCode == GoogleMapController.PLACE_PICKER_REQUEST) {
            if (data == null) {
                return;
            }
            Place place = PlacePicker.getPlace(data, this);
            meetingPlace = place.getName().toString();
            latitude=place.getLatLng().latitude+"";
            longtitude=place.getLatLng().longitude+"";
        }
        bindMeetingPlace();
        controller.onPlaceSelect(this,meetingPlace,latitude,longtitude);
    }

    /**
     * 初始化 AMap 对象
     */
    private void init() {
        showLoading(false);
        //获取位置信息
        LocationManagerProxy mLocationManagerProxy = LocationManagerProxy.getInstance(this);
        //此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        //注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
        //在定位结束后，在合适的生命周期调用destroy()方法
        //其中如果间隔时间为-1，则定位只定一次
        mLocationManagerProxy.requestLocationData(
                LocationProviderProxy.AMapNetwork, -1, 1000, listener);
        mLocationManagerProxy.setGpsEnable(false);

    }

    boolean useGoogleMap = false;
    MapController controller;
    AMapLocationListener listener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getCountry()!=null&&amapLocation.getCountry().equals("中国")) {
                    useGoogleMap = false;
                    if (amapLocation.getProvince()!=null&&amapLocation.getProvince().contains("台湾") || amapLocation.getProvince().contains("香港")
                            || amapLocation.getProvince().contains("澳门")) {
                        useGoogleMap = true;
                    }
                } else {
                    useGoogleMap = true;
                }
            }
            hideLoading();
            //加载地图Fragment
            if (MapUtil.isGmsAvailable()&&(useGoogleMap||MapUtil.debugGoogleMap())) {
                controller=new GoogleMapController();
            } else {
                controller=new GaoDeMapController();
            }
            controller.init(TripDemandInstructionActivity.this,meetingPlace,latitude,longtitude);
        }

        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config=new CustomUiConfig();
        config.mTopbarMiddleAreaName=getString(R.string.trip_group_book);
        config.mTopbarLeftAreaName=getString(R.string.back_icon);
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        saveAction();
        onBackPressed();
    }


}
